﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using DBLClient;
using DBLClient.DBLToolService;
using DBLClient.DBLUserMemberService;
using DBLClient.DBLUserCompanyService;
using DBLClient.DBLUserOrganizationService;
using DBLClient.DBLUserPersonService;
using DBLClient.DBLUserShopService;
using DBLClient.DBLAdminConfigService;

namespace DBLClient.DBLForm
{
    public partial class AddUserForm : Form
    {
        private int usermemberid;
        private string dbltype = string.Empty;
        private string dblno = string.Empty;

        private List<ComboxItem> itemProvince = new List<ComboxItem>();
        private List<ComboxItem> itemCity = new List<ComboxItem>();
        private List<ComboxItem>  itemDistrict = new List<ComboxItem>();
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="type">“A”则为新增，“U”更新</param>
        public AddUserForm(string type,string usermemberid,string dblno)
        {
            

            InitializeComponent();

            InitialAdminLevel();//根据用户等级信息刷新itemprovince,itemcity,itemdistrict

            InitialDblNoType();
            InitialProvince();
            InitialOrgType();
            InitialCategory();
            InitialShopType();
            InitialUserLevel();

            if (type.Equals("A"))
            {
                //新增,do nothing

                InitialAddMode();
                return;
            }
            else if(type.Equals("U"))
            {
                //获取用户账户信息
                this.usermemberid = Int32.Parse(usermemberid);

                UserMemberService user = new UserMemberService();
                DataSet ds = user.GetUserMemberByDBLNo(dblno);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    string loginemail = ds.Tables[0].Rows[0]["loginemail"].ToString();
                    string userlevel = ds.Tables[0].Rows[0]["userlevelid"].ToString();
                    DateTime start = Convert.ToDateTime(ds.Tables[0].Rows[0]["userlevelstart"]);
                    DateTime end = Convert.ToDateTime(ds.Tables[0].Rows[0]["userlevelend"]);

                    //界面赋值
                    textBoxLoginEmail.Text = loginemail;
                    SetComboBoxSelectItemByValue(comboBoxUserLevel, userlevel);
                    dateTimePickerUserStart.Value = start;
                    dateTimePickerUserEnd.Value = end;
                }

                //更新，则需要拿到用户的信息并显示在界面上
                ToolService tool = new ToolService();
                DBLAttribute dblattribute = tool.ParseDBLNo(dblno);

                this.dbltype = dblattribute.DblType;
                this.dblno = dblno;

                SetComboBoxSelectItemByValue(comboBoxDBLNoType, dblattribute.DblType);
                SetComboBoxSelectItemByValue(comboBoxShopType, dblattribute.ShopAttribute);
                SetComboBoxSelectItemByValue(comboBoxOrgType, dblattribute.DblType);

                //地区，以下三句顺序不能变
                SetComboBoxSelectItemByValue(comboBoxProvince, dblattribute.LocationCode.Substring(0, 2));
                SetComboBoxSelectItemByValue(comboBoxCity,dblattribute.LocationCode.Substring(0,4));
                SetComboBoxSelectItemByValue(comboBoxDistrict, dblattribute.LocationCode);
                
                

                //行业大小类，以下两局顺序不能变
                SetComboBoxSelectItemByValue(comboBoxCategory, dblattribute.CategoryCode);
                SetComboBoxSelectItemByValue(comboBoxClassification, dblattribute.ClassificationCode);

                SetComboBoxSelectItemByValue(comboBoxOrgType, dblattribute.OrgTypeCode);
                SetComboBoxSelectItemByValue(comboBoxShopType, dblattribute.ShopAttribute);

                InitialUpdateMode();
            }
        }


        void SetComboBoxSelectItemByValue(ComboBox cb, string Value)
        {
            for (int i = 0; i < cb.Items.Count; ++i)
            {
                ComboxItem dr = (cb.Items[i] as ComboxItem);
                if (dr.Value.Equals(Value))
                {
                    cb.SelectedIndex = i;
                    break;
                }
                else
                    continue;
            }
        }

        private void InitialAddMode()
        {
            groupBoxEdit.Visible = false;
        }

        //更改为更新模式，要把很多按钮和下拉框设置为disable
        private void InitialUpdateMode()
        {
            textBoxLoginEmail.Enabled = false;
            groupBoxAdd.Visible = false;
            comboBoxCategory.Enabled = false;
            comboBoxCity.Enabled = false;
            comboBoxClassification.Enabled = false;
            comboBoxDBLNoType.Enabled = false;
            comboBoxDistrict.Enabled = false;
            comboBoxOrgType.Enabled = false;
            comboBoxProvince.Enabled = false;
            comboBoxShopType.Enabled = false;
            
        }

        private void DisableComboBox()
        {
            comboBoxOrgType.Enabled = false;
            comboBoxOrgType.Items.Clear();
            comboBoxClassification.Enabled = false;
            comboBoxClassification.Items.Clear();
            comboBoxCategory.Enabled = false;
            comboBoxCategory.Items.Clear();
            comboBoxShopType.Enabled = false;
            comboBoxShopType.Items.Clear();
        }

        private void InitialShopType()
        {
            ToolService tool = new ToolService();
            DataSet ds = tool.GetAllShopAttribute();
            if (ds.Tables[0].Rows.Count != 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    ComboxItem item = new ComboxItem();
                    item.Text = dr["name"].ToString();
                    item.Value = dr["code"].ToString();
                    comboBoxShopType.Items.Add(item);
                }
            }
        }

        private void InitialCategory()
        {
            ToolService tool = new ToolService();
            DataSet ds = tool.GetAllCategory();
            if (ds.Tables[0].Rows.Count != 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    ComboxItem item = new ComboxItem();
                    item.Text = dr["categoryname"].ToString();
                    item.Value =dr["categorycode"].ToString();
                    comboBoxCategory.Items.Add(item);
                }
            }
        }

        private void InitialUserLevel()
        {
            AdminConfigService tool = new AdminConfigService();
            DataSet ds = tool.GetAllUserLevel();

            if (ds.Tables[0].Rows.Count != 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    ComboxItem item = new ComboxItem();
                    item.Text = dr["userlevelname"].ToString();
                    item.Value = dr["id"].ToString();
                    comboBoxUserLevel.Items.Add(item);
                }
            }

            comboBoxUserLevel.SelectedIndex = 0;
        }

        private void InitialOrgType()
        {
            ToolService tool = new ToolService();
            DataSet ds = tool.GetAllOrganizationType();
            if (ds.Tables[0].Rows.Count != 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    ComboxItem item = new ComboxItem();
                    item.Text = dr["orgname"].ToString();
                    item.Value = dr["orgcode"].ToString();
                    comboBoxOrgType.Items.Add(item);
                }
            }
        }

        private void InitialDblNoType()
        {
            ComboxItem item1 = new ComboxItem();
            item1.Text = "个人";
            item1.Value = "P";
            comboBoxDBLNoType.Items.Add(item1);

            ComboxItem item2 = new ComboxItem();
            item2.Text = "公司";
            item2.Value = "C";
            comboBoxDBLNoType.Items.Add(item2);

            ComboxItem item3 = new ComboxItem();
            item3.Text = "店铺";
            item3.Value = "S";
            comboBoxDBLNoType.Items.Add(item3);

            ComboxItem item4 = new ComboxItem();
            item4.Text = "机构";
            item4.Value = "O";
            comboBoxDBLNoType.Items.Add(item4);
        }
        private void InitialAdminLevel()
        {
            if (OnlineUserInfo.LEVEL.Equals("ADMIN") || OnlineUserInfo.LEVEL.Equals("ALL"))
            { }
            else
            {
                string[] adminLevelArray = OnlineUserInfo.LEVEL.Split(',');
                foreach (string s in adminLevelArray)
                {
                    ToolService tools = new ToolService();
                    DataSet ds = tools.FindLocationByCode(s);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        string code = s;
                        string fullname = ds.Tables[0].Rows[0]["fullname"].ToString();

                        ComboxItem item = new ComboxItem();
                        item.Text = fullname;
                        item.Value = code;

                        switch (s.Length)
                        {
                            case 2://省
                                itemProvince.Add(item);
                                break;
                            case 4://市
                                itemCity.Add(item);
                                break;
                            case 6://区县
                                itemDistrict.Add(item);
                                break;
                        }

                    }
                }
            }
        }

        private void InitialProvince()
        {
            ToolService tool = new ToolService();
            if (OnlineUserInfo.LEVEL.Equals("ADMIN") || OnlineUserInfo.LEVEL.Equals("ALL"))
            {
                DataSet ds = tool.GetAllProvince();
                if (ds.Tables[0].Rows.Count != 0)
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        ComboxItem item = new ComboxItem();
                        item.Text = dr["provincename"].ToString();
                        item.Value = dr["code"].ToString();
                        comboBoxProvince.Items.Add(item);
                    }
                }
            }
            else
            {
                comboBoxProvince.Items.AddRange(itemProvince.ToArray());
                comboBoxCity.Items.AddRange(itemCity.ToArray());
                comboBoxDistrict.Items.AddRange(itemDistrict.ToArray());
            }

        }

        private void comboBoxProvince_SelectedIndexChanged(object sender, EventArgs e)
        {
            //根据选择的省刷新市
            ComboxItem item = (ComboxItem)comboBoxProvince.SelectedItem;
            string provinceCode = item.Value.ToString();

            ToolService tool = new ToolService();
            DataSet ds = tool.GetCityByProvinceCode(provinceCode);

            if(ds.Tables[0].Rows.Count !=0)
            {
                comboBoxCity.Items.Clear();//清空城市
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    ComboxItem cityitem = new ComboxItem();
                    cityitem.Text = dr["cityname"].ToString();
                    cityitem.Value = dr["citycode"].ToString();
                    comboBoxCity.Items.Add(cityitem);
                } 
            }
            //根据省刷新区，有一些是省直属区，不属于任何市
            DataSet ds2 = tool.GetDistrictByProvinceCode(provinceCode);

            if (ds2.Tables[0].Rows.Count != 0)
            {
                comboBoxDistrict.Items.Clear();//清空城市
                foreach (DataRow dr in ds2.Tables[0].Rows)
                {
                    ComboxItem districtitem = new ComboxItem();
                    districtitem.Text = dr["districtname"].ToString();
                    districtitem.Value = dr["districtcode"].ToString();
                    comboBoxDistrict.Items.Add(districtitem);
                }
            }

            comboBoxCity.Items.AddRange(itemCity.ToArray());
        }

        private void comboBoxCity_SelectedIndexChanged(object sender, EventArgs e)
        {
            //选中市列表，刷新区县列表
            ComboxItem item = (ComboxItem)comboBoxCity.SelectedItem;
            string cityCode = item.Value.ToString();

            ToolService tool = new ToolService();
            DataSet ds = tool.GetDistrictByCityCode(cityCode);

            if (ds.Tables[0].Rows.Count != 0)
            {
                comboBoxDistrict.Items.Clear();//清空城市
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    ComboxItem cityitem = new ComboxItem();
                    cityitem.Text = dr["districtname"].ToString();
                    cityitem.Value = dr["districtcode"].ToString();
                    comboBoxDistrict.Items.Add(cityitem);
                }
            }
            comboBoxDistrict.Items.AddRange(itemDistrict.ToArray());

        }

        private void comboBoxDBLNoType_SelectedIndexChanged(object sender, EventArgs e)
        {
            DisableComboBox();

            ComboxItem item = (ComboxItem)comboBoxDBLNoType.SelectedItem;
            string itemValue = item.Value.ToString();
            switch (itemValue)
            {
                case "P":
                    //个人
                    //do nothing
                    break;
                case "C":
                    comboBoxCategory.Enabled = true;
                    InitialCategory();
                    comboBoxClassification.Enabled = true;
                    
                    break;
                case "S":
                    comboBoxCategory.Enabled = true;
                    InitialCategory();
                    comboBoxClassification.Enabled = true;
                    comboBoxShopType.Enabled = true;
                    InitialShopType();
                    break;
                case "O":
                    comboBoxOrgType.Enabled = true;
                    InitialOrgType();
                    break;
            }
        }

        private void comboBoxCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            //根据行业大类刷新行业细分
            ComboxItem item = (ComboxItem)comboBoxCategory.SelectedItem;
            string categoryCode = item.Value.ToString();

            ToolService tool = new ToolService();
            DataSet ds = tool.GetClassificationByCategory(categoryCode);
            if (ds.Tables[0].Rows.Count != 0)
            {
                comboBoxClassification.Items.Clear();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    ComboxItem newitem = new ComboxItem();
                    newitem.Value = dr["classificationfullcode"].ToString();
                    newitem.Text = dr["classificationname"].ToString();

                    comboBoxClassification.Items.Add(newitem);
                }
            }
        }

        private string ValidateEmail()
        {
            string strPattern = @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
            string email = textBoxLoginEmail.Text;
            if (!System.Text.RegularExpressions.Regex.IsMatch(email, strPattern))
            {
                
                return "请输入正确的EMail格式";
            }

            UserMemberService userMember = new UserMemberService();
            if (userMember.IsLoginEmailAvaible(email))
            {
                
                return "";
            }
            else
            {

                return "Email已经被占用，请换一个EMail";
            }

        }

        private void buttonValidateEmail_Click(object sender, EventArgs e)
        {
            string result = ValidateEmail();
            if (result.Equals(""))
            {
                MessageBox.Show("Email可以被注册");
            }
            else
            {
                MessageBox.Show(result);
            }
           
        }

        private void buttonGenerateDBLNo_Click(object sender, EventArgs e)
        {
            if (GenerateDBLNo().Equals(""))
            {
                return;
            }
            MessageBox.Show("为您预分配的多巴拉代码为："+GenerateDBLNo());
        }

        private bool CheckComboBox(ComboBox combobox)
        {
            if (combobox.SelectedItem == null)
            {

                return false;
            }
            else
            {
                return true;
            }
            
        }

        private string GenerateDBLNo()
        {
            if (comboBoxDistrict.SelectedItem == null)
            {
                MessageBox.Show("没有选择区县");
                return "";
            }
            string district = string.Empty;
            district = ((ComboxItem)comboBoxDistrict.SelectedItem).Value.ToString();

            

            string classification = string.Empty;
            string shoptype = string.Empty;
            string orgtype = string.Empty;

            if (comboBoxDBLNoType.SelectedItem == null)
            {
                MessageBox.Show("没有选择用户类型");
                return "";
            }

            string dblType = ((ComboxItem)comboBoxDBLNoType.SelectedItem).Value.ToString();
            switch (dblType)
            {
                case "C":
                    if (!CheckComboBox(comboBoxClassification))
                    {
                        MessageBox.Show("没有选择行业类型");
                        return "";
                    }
                    classification = ((ComboxItem)comboBoxClassification.SelectedItem).Value.ToString();
                    break;
                case "S":
                    if (!CheckComboBox(comboBoxClassification))
                    {
                        MessageBox.Show("没有选择行业类型");
                        return "";
                    }
                    classification = ((ComboxItem)comboBoxClassification.SelectedItem).Value.ToString();
                    if (!CheckComboBox(comboBoxShopType))
                    {
                        MessageBox.Show("没有选择商铺类型");
                        return "";
                    }
                    shoptype = ((ComboxItem)comboBoxShopType.SelectedItem).Value.ToString();
                    break;
                case "O":
                    if (!CheckComboBox(comboBoxOrgType))
                    {
                        MessageBox.Show("没有选择组织类型");
                        return "";
                    }
                    orgtype = ((ComboxItem)comboBoxOrgType.SelectedItem).Value.ToString();
                    break;
                case "P":
                    break;
                default:
                     MessageBox.Show("请选择用户类型");
                     break;
                    
            }

            ToolService tool = new ToolService();
            return tool.GenerateDBLNo(district, classification, shoptype, dblType, orgtype);
        }

        private bool IsRepeatPassword()
        {
            //验证密码符合标准
            string password = textBoxPassword.Text;
            string repeatpassword = textBoxRepeatPassword.Text;
            if (!repeatpassword.Equals(password))
            {
                MessageBox.Show("两次输入的密码不相同");
                return false;
            }
            if (password.Length < 6 || password.Length > 15)
            {
                MessageBox.Show("密码长度允许范围是6-15位");
                return false;
            }

            return true;
            
        }

        private void buttonAddUser_Click(object sender, EventArgs e)
        {
            //把用户写入
            DateTime dt = DateTime.Today.AddDays(66);

            string result = ValidateEmail();
            
            if (!result.Equals(""))
            {
                MessageBox.Show(result);
                return;
            }

            string email = textBoxLoginEmail.Text;
            string dblno = GenerateDBLNo();
            
            if (dblno.Equals(""))
            {
                return;
            }

            if (!IsRepeatPassword())
            {
                return;
            }
            string password = textBoxPassword.Text;

            if (comboBoxUserLevel.SelectedItem == null)
            {
                MessageBox.Show("请选择用户等级");
                return;
            }
            int userlevelid = Convert.ToInt32(((ComboxItem)comboBoxUserLevel.SelectedItem).Value);

            DateTime userlevelstart = dateTimePickerUserStart.Value;
            DateTime userlevelend = dateTimePickerUserEnd.Value;

            string dblType = ((ComboxItem) comboBoxDBLNoType.SelectedItem).Value.ToString();

            //以上是准备数据
            //下面是开始准备插入数据库
            int usermemberaffect = 0;
            UserMemberService user = new UserMemberService();
            try
            {
                usermemberaffect = user.AddUserMember(dblno, email, password, userlevelid, dblType, userlevelstart.ToString(), userlevelend.ToString());
            }
            catch (Exception ee) 
            {
                MessageBox.Show("新增失败"+ee.Message);
                return;
            }

            if (usermemberaffect == 1)
            {
                MessageBox.Show("新增成功");
            }
            //if (usermemberaffect == 1)
            //{ //成功插入
            //    DataSet ds = user.GetUserMemberByDBLNo(dblno);
            //    int id = (int)ds.Tables[0].Rows[0]["id"];
            //    int useraffect = 0;
            //    switch (dblType)
            //    {
            //        case "C":
            //            UserCompanyService company = new UserCompanyService();
            //            useraffect = company.AddUpdateUserCompany(id, dblno, "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");
            //            break;
            //        case "P":
            //            UserPersonService person = new UserPersonService();
            //            useraffect = person.AddUpdateUserPerson(id, dblno, "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");
            //            break;
            //        case "O":
            //            UserOrganizationService org = new UserOrganizationService();
            //            useraffect = org.AddUpdateUserOrganization(id, dblno, "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");
            //            break;
            //        case "S":
            //            UserShopService shop = new UserShopService();
            //            useraffect = shop.AddUpdateUserShop(id, dblno, "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");
            //            break;
            //    }
            //    if (useraffect == 1)
            //    {
            //        MessageBox.Show("新增用户成功,用户的多巴拉码为:"+dblno);
            //        return;
            //    }

            //}
            //else
            //{
            //    MessageBox.Show("新增用户不成功，请重试");
            //}
        }

        private void comboBoxUserLevel_SelectedIndexChanged(object sender, EventArgs e)
        {
            //根据用户的等级更改时间
            if (Convert.ToInt32(((ComboxItem)comboBoxUserLevel.SelectedItem).Value) == 0)
            {
                //0为固定的默认普通用户
                dateTimePickerUserEnd.Value = DateTime.Now.AddYears(10);
            }
            else
            {
                dateTimePickerUserEnd.Value = DateTime.Now.AddYears(1);
            }
        }

        private void buttonUpdatePassword_Click(object sender, EventArgs e)
        {
            //修改密码
            if (!IsRepeatPassword())
            {
                return;
            }

            UserMemberService user = new UserMemberService();
            int affectnum = user.ChangePassword(usermemberid,textBoxPassword.Text);

            if (affectnum == 1)
            {
                MessageBox.Show("更改密码成功");
            }
            else
            {
                MessageBox.Show("更改密码失败");
            }
        }

        private void buttonUpdateUserLevel_Click(object sender, EventArgs e)
        {
            //修改用户等级和用户等级时间段
            UserMemberService user = new UserMemberService();
            int userlevelid = Convert.ToInt32(((ComboxItem)comboBoxUserLevel.SelectedItem).Value);
            DateTime start = dateTimePickerUserStart.Value;
            DateTime end = dateTimePickerUserEnd.Value;
            int affectnum = user.ChangeUserLevel(usermemberid, userlevelid, start.ToString(), end.ToString());

            if (affectnum == 1)
            {
                MessageBox.Show("更改用户等级和有效期成功");
            }
            else
            {
                MessageBox.Show("更改用户等级和有效期失败");
            }

        }

        private void buttonToUserInfo_Click(object sender, EventArgs e)
        {
            switch (dbltype)
            {
                case "C":
                    EditUserCompanyForm company = new EditUserCompanyForm(usermemberid,dblno);
                    company.Show();
                    break;
                case "S":
                    EditUserShopForm shop = new EditUserShopForm(usermemberid, dblno);
                    shop.Show();
                    break;
                case "P":
                    EditUserPersonForm person = new EditUserPersonForm(usermemberid, dblno);
                    person.Show();
                    break;
                case "O":
                    EditUserOrganizationForm org = new EditUserOrganizationForm(usermemberid, dblno);
                    org.Show();
                    break;
            }
        }
    }
}
